package com.esfak47.mediafetcher.app.extension;

import com.esfak47.common.extension.Activate;
import com.esfak47.common.extension.ExtensionFactory;
import com.esfak47.common.utils.ConcurrentHashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.Set;

/**
 * SpringExtensionFactory
 *
 * @author tony
 */
public class SpringExtensionFactory implements ExtensionFactory {
    private final static Logger logger = LoggerFactory.getLogger(SpringExtensionFactory.class);

    private static final Set<ApplicationContext> contexts = new ConcurrentHashSet<ApplicationContext>();

    public static void addApplicationContext(ApplicationContext context) {
        contexts.add(context);
    }

    public static void removeApplicationContext(ApplicationContext context) {
        contexts.remove(context);
    }

    @Override
    @Activate(before = "spi")
    @SuppressWarnings("unchecked")
    public <T> T getExtension(Class<T> type, String name) {

        logger.info("finding {} for type name {}", type.getName(), name);
        for (ApplicationContext context : contexts) {
            if (context.containsBean(name)) {
                Object bean = context.getBean(name);
                if (type.isInstance(bean)) {
                    return (T)bean;
                }
            }
        }

        logger.info("find failed for {} of name ", type.getName(), name);
        return null;
    }

}